package com.sks.web.action.house;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.stereotype.Controller;

import com.sks.bean.PageView;
import com.sks.bean.QueryResult;
import com.sks.bean.pojo.Area;
import com.sks.service.house.AreaService;
import com.sks.utils.SiteUrl;
import com.sks.utils.StringUtil;
import com.sks.web.action.BasicAction;
import com.sks.web.action.privilege.Permission;
import com.sks.web.formbean.house.AreaForm;

import flexjson.JSONSerializer;

@Controller("/cms/house/area")
public class AreaAction extends BasicAction {
	@Resource(name = "areaServiceBean")
	private AreaService service;

	// 查询一级区域，如天河、越秀等...
	@Permission(module = "info", privilege = "view")
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		QueryResult<Area> qr = null;
		AreaForm formbean = (AreaForm) form;
		PageView<Area> pageView = new PageView<Area>(12, formbean.getPage());
		StringBuffer jpql = new StringBuffer(" 1=1");
		List<Object> params = new ArrayList<Object>();
		if ("true".equals(formbean.getQuery())) {// 进行查询操作
			if (formbean.getName() != null
					&& !"".equals(formbean.getName().trim())) {
				params.add("%" + formbean.getName() + "%");
				jpql.append(" and o.name like ?" + params.size());
			}
		}
		if (formbean.getIsTop()) {
			jpql.append(" and o.parentArea is null");
		} else {
			if (null != formbean.getParentAreaId()
					&& 0 != formbean.getParentAreaId()) {
				Area parent = service.find(formbean.getParentAreaId());
				params.add(parent);
				jpql.append(" and o.parentArea = ?" + params.size());
			} else {
				jpql.append(" and o.parentArea is not null");
			}
		}
		qr = service.getScrollData(pageView.getFirstResult(), pageView
				.getMaxresult(), jpql.toString(), params.toArray());
		pageView.setQueryResult(qr);
		request.setAttribute(PAGEVIEW, pageView);
		request.setAttribute("isTop", formbean.getIsTop());
		this.setReadOnly(request, "list");
		return mapping.findForward(LIST);
	}

	@Permission(module = "info", privilege = "update")
	public ActionForward addUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		AreaForm formbean = (AreaForm) form;
		if (!formbean.getIsTop()) {
			getTopArea(request);
		}
		formbean.setMethod(ADD);
		request.setAttribute("isTop", formbean.getIsTop());
		return mapping.findForward(EDIT);
	}

	public void beforeedit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.beforeadd(mapping, form, request, response);
	}

	@Permission(module = "info", privilege = "view")
	public ActionForward editUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		AreaForm formbean = (AreaForm) form;
		Area area = service.find(formbean.getAreaId());
		if (!formbean.getIsTop()) {
			getTopArea(request);
			formbean.setParentAreaId(area.getParentArea().getAreaId());
		}
		copyProperties(area, formbean);
		formbean.setMethod(EDIT);
		request.setAttribute("isTop", formbean.getIsTop());
		
		this.setReadOnly(request, "editUI");
		
		return mapping.findForward(EDIT);
	}

	public void beforeadd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionMessages errors = new ActionMessages();
		AreaForm formbean = (AreaForm) form;
		
		if (StringUtil.isEmpty(formbean.getName())) {
			errors.add("name", new ActionMessage("errors.required", getMessage("info.area.field.name")));
		}
		
		List params = new ArrayList();
		params.add(formbean.getName());
		StringBuffer jpql = new StringBuffer("o.name = ?" + params.size());
		if (EDIT.equals(formbean.getMethod())) {
			params.add(formbean.getAreaId());
			jpql.append(" and o.areaId <> ?" + params.size());
		}
		QueryResult<Area> m = service.getScrollData(-1, -1, jpql.toString(),
				params.toArray());
		if (null != m && m.getResultlist().size() > 0) {
			// 提示信息
			errors.add("name", new ActionMessage("errors.repeat", getMessage("info.area.field.name")));
			request.setAttribute(ACTION, formbean.getMethod());
			request.setAttribute("isTop", formbean.getIsTop());
			if (!formbean.getIsTop()) {
				getTopArea(request);
			}
		}
		saveErrors(request, errors);
	}

	@Permission(module = "info", privilege = "update")
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AreaForm formbean = (AreaForm) form;
		Boolean isTop = formbean.getIsTop();
		Area area = new Area(formbean.getName());
		copyProperties(formbean, area);
		if (isTop) {
			area.setParentArea(null);
		} else {
			Area parent = service.find(formbean.getParentAreaId());
			area.setParentArea(parent);
		}
		area.setAreaId(null);
		service.save(area);
		request.setAttribute(MESSAGE, getMessage("display.add") + getMessage("info.area." + (isTop ? "1" : "2")) + getMessage("display.success"));
		request.setAttribute("urladdress", SiteUrl.readUrl(
				"com.sks.web.action.house.area", new Object[] { isTop }));
		return mapping.findForward(MESSAGE);
	}

	@Permission(module = "info", privilege = "update")
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AreaForm formbean = (AreaForm) form;
		Boolean isTop = formbean.getIsTop();
		Area area = service.find(formbean.getAreaId());
		copyProperties(formbean, area);
		if (isTop) {
			area.setParentArea(null);
		} else {
			Area parent = service.find(formbean.getParentAreaId());
			area.setParentArea(parent);
		}
		service.update(area);
		request.setAttribute(MESSAGE, getMessage("display.edit") + getMessage("info.area." + (isTop ? "1" : "2")) + getMessage("display.success"));
		request.setAttribute("urladdress", SiteUrl.readUrl(
				"com.sks.web.action.house.area", new Object[] { isTop }));
		return mapping.findForward(MESSAGE);
	}

	@Permission(module = "info", privilege = "update")
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AreaForm formbean = (AreaForm) form;
		service.delete(formbean.getAreaId());
		request.setAttribute(MESSAGE, getMessage("display.delete") + getMessage("info.area." + (formbean.getIsTop() ? "1" : "2")) + getMessage("display.success"));
		request.setAttribute("urladdress", SiteUrl.readUrl(
				"com.sks.web.action.house.area", new Object[] { formbean.getIsTop() }));
		return mapping.findForward(MESSAGE);
	}

	@Permission(module = "info", privilege = "view")
	public ActionForward queryUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AreaForm formbean = (AreaForm) form;
		request.setAttribute("isTop", null == formbean.getIsTop() ? false
				: formbean.getIsTop());
		return mapping.findForward(QUERY);
	}
	
	private void getTopArea(HttpServletRequest request) {
		List<Area> topArea = service.findTopArea(null);
		request.setAttribute("topArea", topArea);
	}
	
	/**
	 * 区域二级联动
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Permission(module = "info", privilege = "view")
	public ActionForward getAreasByTopId(ActionMapping mapping, ActionForm form,
         HttpServletRequest request, HttpServletResponse response) throws Exception {
	   AreaForm formbean = (AreaForm) form;
	   if (null == formbean.getAreaId() || 0 == formbean.getAreaId()) {
		   response.getWriter().write("[{\"name\":\"\",\"areaId\":\"\"}]");
		   return null;
	   }
	   Area topArea = service.find(formbean.getAreaId());
	   List<Area> areas = topArea.getAreas();
	   JSONSerializer json = new JSONSerializer();
	   String jsonStr = json.exclude("*.class", "areas", "parentArea", "visible", "remark").include("areaId", "name").serialize(areas);
	   response.getWriter().write(jsonStr);
	   return null;
   }
	
	// 分页测试，以后需要删除
	public ActionForward list2(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		AreaForm formbean = (AreaForm) form;
		PageView<Area> pageView = new PageView<Area>(formbean.getPageSize(), formbean.getPage());
		QueryResult<Area> qr = service.getScrollData(pageView.getFirstResult(), pageView.getMaxresult());
		pageView.setQueryResult(qr);
		request.setAttribute(PAGEVIEW, pageView);
		return mapping.findForward("list2");
	}
}
